package healththink
import grails.plugins.springsecurity.*

class UserController {
    def springSecurityService
    
    @Secured(['ROLE_OWNER', 'ROLE_MODERATOR', 'IS_AUTHENTICATED_FULLY'])
    def scaffold = true
    
    def mobileService
    
    def afterInterceptor = [action: this.&handleMobile]
	 
    private handleMobile(model, modelAndView) {
       
        
            if (modelAndView && mobileService.detect(request)) {

                modelAndView.viewName = '/mobile/' + modelAndView.viewName          

            }
	 
    }

    @Secured(['IS_AUTHENTICATED_ANONYMOUSLY'])
    def login = {}
    
    @Secured(['IS_AUTHENTICATED_ANONYMOUSLY'])
    def doLogin = {
        def user = User.findWhere(email:params['email'],
            password:params['password'])
        session.user = user
        if(user)
            redirect(controller: 'facility', action:'view', params: [name: session.name])
        else
            redirect(controller:'user',action:'login')
    }
    
    @Secured(['IS_AUTHENTICATED_ANONYMOUSLY'])
    def index() {
        redirect(action: "list")
    }
    
    @Secured(['IS_AUTHENTICATED_ANONYMOUSLY'])
    def register = {
        if(!params.register)return
        
        String pass1 = params.password
        String pass2 = params.repeatPassword
        def user = new User(params)
        if(pass1 != pass2){
            user.password = ""
            flash.message = "Error: Passwords Did Not Match"
            return [user: user]
        }
        if(user.validate()){
            String Contributor = "ROLE_" + UserType.Contributor.toString().toUpperCase()
            def contributorRole = SecRole.findByAuthority(Contributor)
            user.save()
            SecUserSecRole.create user, contributorRole
            if(mobileService.detect(request)){
                forward controller: "login", action: "auth"
            }else{
                redirect(controller: "login", action: "auth")
            }
        }else{
            user.password = ""
            return [user: user]
        }
    }
    
    @Secured(['IS_AUTHENTICATED_ANONYMOUSLY'])
    def view = {    
        def user = User.get(springSecurityService.principal.id)
        def role = springSecurityService.principal.authorities
        def upgradeRequest = UserUpgradeRequest.findByUser(user)
        def madeRequest = false
        if(upgradeRequest){
            madeRequest = true
        }
        def recentPosts = Post.findAllByUser(user, [max: 5, sort: "dateCreated", order: "desc"])
        [user: user, role: role, recentPosts: recentPosts, madeRequest: madeRequest]
    }
    
    @Secured(['ROLE_OWNER', 'ROLE_MODERATOR', 'ROLE_CONTRIBUTOR', 'IS_AUTHENTICATED_FULLY'])
    def editInfo = {
        if(!params.submit){
            def user = User.findByUsername(params.username)
            return [user: user]
        }
        String pass1 = params.password
        String pass2 = params.repeatPassword
        def user = User.findByUsername(params.username)
        if(pass1 != pass2){
            user.password = ""
            flash.message = "Error: Passwords Did Not Match"
            return [user: user]
        }
        user.properties = params
        if(user.validate()){
            user.save()
            if(mobileService.detect(request)){
                forward action: "view"
            }else{
                redirect(action: "view")
            }
        }else{
            user.password = ""
            return [user: user]
        }
    }
    
    def requestUpgrade = {
        def user = User.get(springSecurityService.principal.id)
        def roles = springSecurityService.principal.authorities*.authority
        def contributorRole = SecRole.findByAuthority("ROLE_" + UserType.Contributor.toString().toUpperCase())
        def moderatorRole = SecRole.findByAuthority("ROLE_" + UserType.Moderator.toString().toUpperCase())
        def ownerRole = SecRole.findByAuthority("ROLE_" + UserType.Owner.toString().toUpperCase())
        if(roles.contains("ROLE_CONTRIBUTOR")){
            def upgrade = new UserUpgradeRequest(user: user, role: moderatorRole)
            upgrade.save()
        }else if(roles.contains("ROLE_MODERATOR")){
            def upgrade = new UserUpgradeRequest(user: user, role: ownerRole)
            upgrade.save()
        }
        if(mobileService.detect(request)){
            forward action: "view"
        }else{
            redirect(action: "view")
        }
    }
    
    def viewUpgrades = {
        def requestList = UserUpgradeRequest.list()
        [requestList: requestList]
    }
    
    def upgradeUser = {
        def user = User.findByUsername(params.username)
        def role = SecRole.findByAuthority(params.role)
        def request = UserUpgradeRequest.findByUserAndRole(user, role)
        if(params.role == "ROLE_MODERATOR"){
            println "removing contributor role"
            SecUserSecRole.remove(user, SecRole.findByAuthority("ROLE_CONTRIBUTOR"))
        }else if(params.role == "ROLE_OWNER"){
            println "removing moderator role"
            SecUserSecRole.remove(user, SecRole.findByAuthority("ROLE_MODERATOR"))
        }
        request.delete()
        SecUserSecRole.create(user, role)
        if(mobileService.detect(request)){
            forward action: "view"
        }else{
            redirect(action: "view")
        }
    }
}
